package com.olddriver.crm.web.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.olddriver.crm.util.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/*使用ajax请求需要使用自定义的表单过滤器*/
public class ExtendFormAuthenticalFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        /*返回json result*/
        response.getWriter().print(new ObjectMapper().writeValueAsString(JsonResult.success()));
        /*不再执行后续过滤器及contoller*/
        /*父类的isFilterChainContinued()方法*/
        return false;
    }

    /*覆盖父类方法,重新登陆时注销就用户*/
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //所有经过authc认证过滤器的请求均会经过该方法,判断是否为登陆请求,是则注销,否则不处理
        if (isLoginRequest(request, response)) {
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                subject.logout();
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        e.printStackTrace();
        String errorName = e.getClass().getName();
        try {
            if (IncorrectCredentialsException.class.getName().equals(errorName)) {
                response.getWriter().print(new ObjectMapper().writeValueAsString(JsonResult.diyFaliure("密码错误")));
            } else if (UnknownAccountException.class.getName().equals(errorName)) {
                response.getWriter().print(new ObjectMapper().writeValueAsString(JsonResult.diyFaliure("无效用户")));
            } else {
                response.getWriter().print(new ObjectMapper().writeValueAsString(JsonResult.diyFaliure("系统繁忙")));
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
